package com.kfm.servlet.day04;

import com.kfm.servlet.day04.db.DBUtils;
import com.kfm.servlet.day04.model.FileModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadv2")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        DBUtils<FileModel> dbUtils = new DBUtils(1);

        String sql = "select id, path, type, name from file where id = ?";
        FileModel o = dbUtils.selectOne(sql, FileModel.class, id);

        String path = o.getPath();
        File file = new File(Constants.UPLOAD_BASE_PATH, path);
        if (file.isFile()){
            resp.setContentType(o.getType());
            resp.setHeader("Content-Disposition", "attachment;filename=" + o.getName());
            FileInputStream fis = new FileInputStream(file);
            fis.transferTo(resp.getOutputStream());
            fis.close();
        }
    }
}
